package com.xiaohong.search.test;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 向索引更新数据的Demo
 */
public class ElasticSearchUpdate {

	public static void main(String[] args) throws IOException {
		ElasticSearchUpdate update = new ElasticSearchUpdate();
		update.updateDoc();
		System.out.println("更新完成");
	}


	public void updateDoc() throws IOException {
		//获取连接
		//es的更新有两种情况,知道id和不知道id的情况
		//UpdateRequest 知道id
		//UpdateByQueryRequest 不知道id


		//当es用用户名和密码连接时
		//初始化ES操作客户端
		final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
		credentialsProvider.setCredentials(AuthScope.ANY,
				new UsernamePasswordCredentials("elastic", "123456"));  //es账号密码（默认用户名为elastic）
		RestHighLevelClient client =new RestHighLevelClient(
				RestClient.builder(new HttpHost("192.168.6.1",9200,"http")).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
					public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
						httpClientBuilder.disableAuthCaching();
						return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
					}
				})
		);
		//TODO 当es无密码时可以直接使用下面这个创建客户端
		//RestHighLevelClient client =  new RestHighLevelClient(RestClient.builder(new HttpHost(
		//		"192.168.6.1",9200,"http"
		//)));

		Map<String, Object> jsonMap = new HashMap<>();
		jsonMap.put("qq", "黑骑五户");
		//知道id时
		UpdateRequest updateRequest = new UpdateRequest("sse_test","1").doc(jsonMap);
		//TODO 不知道id时
		//UpdateByQueryRequest request = new UpdateByQueryRequest("sse_test");
		//request.setDocTypes("student");
		//request.setQuery(new TermQueryBuilder("name","黑骑一户"));
		//client.updateByQuery(request,RequestOptions.DEFAULT);

		updateRequest.docAsUpsert(true);
		client.update(updateRequest, RequestOptions.DEFAULT);

	}
}
